import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:family_app/src/features/finance/models/monthly_bill_model.dart';
import 'package:family_app/src/features/finance/models/yearly_stats_model.dart';
import 'package:family_app/src/features/finance/providers/finance_provider.dart';
import 'package:family_app/src/features/finance/widgets/month_summary_tile.dart';
import 'package:family_app/src/theme/app_theme.dart';

/// 记账本详情页面
/// 按照12月-1月倒序排序，可以选择年份
/// 当前年份只显示到当前月份，往年显示全部12个月
class FinanceDetailTab extends ConsumerStatefulWidget {
  const FinanceDetailTab({Key? key}) : super(key: key);

  @override
  ConsumerState<FinanceDetailTab> createState() => _FinanceDetailTabState();
}

class _FinanceDetailTabState extends ConsumerState<FinanceDetailTab> {
  // 当前年份和月份
  late int _currentYear;
  late int _currentMonth;
  // 选择的年份
  late int _selectedYear;

  @override
  void initState() {
    super.initState();
    final now = DateTime.now();
    _currentYear = now.year;
    _currentMonth = now.month;
    _selectedYear = _currentYear;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // 年份选择器
        _buildYearSelector(),
        
        // 月份列表（使用月度账单数据）
        Expanded(
          child: _buildMonthlyBillList(),
        ),
      ],
    );
  }

  /// 构建年份选择器
  Widget _buildYearSelector() {
    // 生成最近5年的年份列表，用于选择
    final years = List.generate(5, (index) => _currentYear - index);
    
    // 获取当前选中年份的统计数据
    final yearlyStatsAsync = ref.watch(yearlyStatsProvider((_selectedYear, 1)));

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.3),
      child: Column(
        children: [
          // 第一行：年份选择
          Row(
            children: [
              Text(
                '选择年份：',
                style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.bold),
              ),
              SizedBox(width: 8.w),
              DropdownButton<int>(
                value: _selectedYear,
                items: years.map((year) {
                  return DropdownMenuItem<int>(
                    value: year,
                    child: Text('$year 年'),
                  );
                }).toList(),
                onChanged: (value) {
                  if (value != null) {
                    setState(() {
                      _selectedYear = value;
                    });
                  }
                },
                underline: Container(),
                style: TextStyle(
                  fontSize: 16.sp, 
                  color: AppTheme.primaryColor, 
                  fontWeight: FontWeight.bold
                ),
              ),
            ],
          ),
          SizedBox(height: 8.h),
          // 第二行：年度统计
          yearlyStatsAsync.when(
            data: (stats) => Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                // 总收入
                _buildYearStatisticFromStats(
                  '总收入',
                  stats?.totalIncomeMoney ?? 0,
                  Colors.green,
                ),
                // 分隔线
                Container(
                  width: 1,
                  height: 30.h,
                  color: Colors.grey[300],
                ),
                // 总支出
                _buildYearStatisticFromStats(
                  '总支出',
                  stats?.totalExpenseMoney ?? 0,
                  Colors.red,
                ),
              ],
            ),
            loading: () => Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                _buildLoadingStatistic('总收入'),
                Container(
                  width: 1,
                  height: 30.h,
                  color: Colors.grey[300],
                ),
                _buildLoadingStatistic('总支出'),
              ],
            ),
            error: (error, stack) => Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                _buildErrorStatistic('总收入'),
                Container(
                  width: 1,
                  height: 30.h,
                  color: Colors.grey[300],
                ),
                _buildErrorStatistic('总支出'),
              ],
            ),
          ),
        ],
      ),
    );
  }
  
  /// 构建年度统计数据项（从统计数据）
  Widget _buildYearStatisticFromStats(String label, int amount, Color color) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Text(
          label,
          style: TextStyle(fontSize: 12.sp, color: Colors.grey[600]),
        ),
        SizedBox(height: 2.h),
        Text(
          '¥${amount.toStringAsFixed(2)}',
          style: TextStyle(
            fontSize: 14.sp,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
      ],
    );
  }

  /// 构建加载中的统计数据项
  Widget _buildLoadingStatistic(String label) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Text(
          label,
          style: TextStyle(fontSize: 12.sp, color: Colors.grey[600]),
        ),
        SizedBox(height: 2.h),
        SizedBox(
          width: 20.w,
          height: 20.h,
          child: CircularProgressIndicator(
            strokeWidth: 2,
            valueColor: AlwaysStoppedAnimation<Color>(Colors.grey),
          ),
        ),
      ],
    );
  }

  /// 构建错误状态的统计数据项
  Widget _buildErrorStatistic(String label) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Text(
          label,
          style: TextStyle(fontSize: 12.sp, color: Colors.grey[600]),
        ),
        SizedBox(height: 2.h),
        Text(
          '加载失败',
          style: TextStyle(fontSize: 12.sp, color: Colors.red),
        ),
      ],
    );
  }

  /// 构建月份列表（使用月度账单数据）
  Widget _buildMonthlyBillList() {
    // 使用yearlyBillListProvider获取月度账单数据
    final monthlyBillsAsync = ref.watch(yearlyBillListProvider((_selectedYear, 1)));

    return monthlyBillsAsync.when(
      data: (monthlyBills) {
        // 如果没有数据，显示空状态
        if (monthlyBills.isEmpty) {
          return _buildEmptyState();
        }

        // 按月份排序（降序）
        final sortedBills = List<MonthlyBillModel>.from(monthlyBills)
          ..sort((a, b) => int.parse(b.month).compareTo(int.parse(a.month)));

        // 过滤月份：如果是当前年份，只显示到当前月份
        final filteredBills = _selectedYear == _currentYear
            ? sortedBills.where((bill) => int.parse(bill.month) <= _currentMonth).toList()
            : sortedBills;

        return ListView.builder(
          padding: EdgeInsets.only(bottom: 16.h),
          itemCount: filteredBills.length,
          itemBuilder: (context, index) {
            final bill = filteredBills[index];
            return MonthSummaryTile(
              year: _selectedYear,
              month: int.parse(bill.month),
              bill: bill, // 传递完整的bill对象
            );
          },
        );
      },
      loading: () => const Center(child: CircularProgressIndicator()),
      error: (error, stack) => Center(
        child: Text('加载账单失败: $error', style: TextStyle(color: Colors.red)),
      ),
    );
  }

  /// 构建空状态界面
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.receipt_long_outlined, size: 64.r, color: Colors.grey),
          SizedBox(height: 16.h),
          Text(
            '暂无账单记录',
            style: TextStyle(fontSize: 16.sp, color: Colors.grey),
          ),
          SizedBox(height: 8.h),
          Text(
            '$_selectedYear年暂无账单数据',
            style: TextStyle(fontSize: 14.sp, color: AppTheme.textSecondaryColor),
          ),
        ],
      ),
    );
  }
}
